<template>
  <div style="display: inline-block;text-align: left;">
    <el-button type="primary" size="small" @click="openEdit(row_id)">{{ $t('table.edit') }}</el-button>
    <el-dialog v-if="dialogTableVisible" :visible.sync="dialogTableVisible" top="1%" :title="$t('table.edit')" width="40%">
      <el-form ref="formData" :model="formData" :rules="rules" label-position="right" label-width="auto" v-loading="loading">
        <el-form-item :label="$t('table.worker_name')" prop="name">
          <el-col>
            <el-input v-model="formData.name" label="right" type="text" />
          </el-col>
        </el-form-item>
        <el-form-item :label="$t('table.worker_id')" prop="person_id">
          <el-col>
            <el-input v-model="formData.person_id" disabled label="right" type="text" />
          </el-col>
        </el-form-item>
        <el-form-item :label="$t('staff.employee_card_id')" prop="employee_card_id">
          <el-col>
            <el-input v-model="formData.employee_card_id" label="right" type="text" />
          </el-col>
        </el-form-item>
        <!-- <el-form-item label="注册时间" prop="register_time">
          <el-col :span="12">
            <el-input
              v-model="formData.register_time"
              label="right"
              type="text"
              placeholder="请输入注册时间"
            />
          </el-col>
        </el-form-item> -->
        <el-form-item :label="$t('table.avatar')" prop="face_pic">
          <el-alert :title="$t('staff.img_tip')" type="warning" show-icon
            style="margin-bottom: 10px; line-height: 20px; width: 380px" :close-text="$t('staff.know')" />
          <el-upload :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :http-request="img_update"
            class="avatar-uploader" action="">
            <img v-if="formData.face_pic" :src="base64Prefix + formData.face_pic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <!-- <el-form-item :label="$t('staff.img_enc')" prop="image_enc">
          <el-select v-model="formData.image_enc" :placeholder="$t('validation.is_encrypt')">
            <el-option :label="$t('staff.yes')" value="true" />
            <el-option :label="$t('staff.no')" value="false" />
          </el-select>
        </el-form-item> -->
        <el-form-item :label="$t('staff.sex')" prop="gender">
          <el-select v-model="formData.gender">
            <div v-if="formData.gender!=''"><el-option  :label="$t('staff.man')" value="1" />
            <el-option   :label="$t('staff.women')" value="0" /></div>
            
            <el-option  v-else :label="$t('staff.women')" value="" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.company')" prop="company_id">
          <el-select v-model="formData.company_id" @change="CompanyIndex(formData.company_id)">
            <el-option v-for="(item, index) in Company_list" :key="index" :label="item.company" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.department')" prop="department_id">
          <el-select v-model="formData.department_id">
            <el-option v-for="(item, index) in department_list" :key="index" :label="item.department" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item :label="$t('staff.permiss_role')" prop="shop_role_id">
          <el-select v-model="formData.shop_role_id">
            <el-option v-for="(item, index) in rolePermissions" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item :label="$t('staff.shcedule')" prop="schedule_id">
          <el-select v-model="formData.schedule_id">
            <el-option v-for="(item, index) in defaultShift" :key="index" :label="item.name" :value="item.schedule_id" />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item :label="$t('staff.is_departure')" prop="quit">
          <el-select v-model="formData.quit">
            <el-option :label="$t('staff.yes')" value="1" />
            <el-option :label="$t('staff.no')" value="0" />
          </el-select>
        </el-form-item> -->
        <el-form-item :label="$t('table.remark')" prop="description">
          <el-col>
            <el-input v-model="formData.description" label="right" type="text" />
          </el-col>
        </el-form-item>
        <el-form-item :label="$t('staff.access_authorization')" prop="atclik">
          <el-select v-model="formData.atclik" multiple>
            <!-- <el-option :label="$t('staff.all_device')" value="*" /> -->
            <el-option v-for="(item, index) in Equipment" :key="index" :label="item.device_name" :value="item.sn" />
          </el-select>
        </el-form-item>
        <el-form-item align="right">
          <div>
            <el-button type="primary" size="small" @click="submitForm(row_id)">{{ $t('table.complete') }}</el-button>
            <el-button size="small" @click="closeDia()">{{ $t('table.cancel') }}</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import store from "@/store";
import {
  employee_info,
  employee_edit,
  department_get_select,
  push_get_list,
  device_auth_get_select,
} from "@/api/user_manage/user_manage";
import { client } from "@/utils/alioss";
import { get_list } from "@/api/organization_manage/organization_manage";
// 获取默认班次
import { get_schedule_list } from "@/api/attendance_management/attendanceShift";
// 角色数据
import { getList } from "@/api/shop_admin_auth/shopRole";

export default {
  props: {
    row_id: {
      type: Number,
      default: function () {
        return null;
      },
    },
    company_id: {
      type: Number,
      default: function () {
        return null;
      },
    },
  },
  data() {
    return {
      loading: true,
      formSn: null,
      atclik: [],
      EquipmentList: [],
      Equipment: [],
      company_id_id: null,
      is_img: true,
      base64Prefix: "data:image/jpg;base64,",
      company_name: null,
      Company_list: null,
      department_list: null,
      dialogTableVisible: false,
      formData: {
      },
      valList: null,
      base64: null,
      imageUrl: "",
      newTime: null,
      defaultShift: null,
      rolePermissions: null,
      rules: {
        face_pic: [{ required: true, message: "请填写头像", trigger: "blur" }],
        // company_id: [
        //   {
        //     required: true,
        //     message: this.$t('validation.company'),
        //     trigger: 'blur'
        //   }
        // ],
        // employee_card_id: [
        //   {
        //     required: true,
        //     message: this.$t('validation.employee_card'),
        //     trigger: 'blur'
        //   }
        // ],
        // department_id: [
        //   { required: true, message: this.$t('validation.department1'), trigger: 'blur' }
        // ],
        person_id: [
          {
            required: true,
            message: this.$t("validation.worker_id"),
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: this.$t("validation.worker_name"),
            trigger: "blur",
          },
        ],
        atclik: [
          { required: true, message: this.$t("staff.access_authorization"), trigger: 'blur' }
        ]
        // image_enc: [
        //   {
        //     required: true,
        //     message: this.$t('validation.is_encrypt'),
        //     trigger: 'blur'
        //   }
        // ],
        // gender: [{ required: true, message: this.$t('validation.sex'), trigger: 'blur' }],
        // shop_role_id: [
        //   {
        //     required: true,
        //     message: this.$t('validation.role'),
        //     trigger: 'blur'
        //   }
        // ],
        // schedule_id: [
        //   {
        //     required: true,
        //     message: this.$t('validation.shcedule'),
        //     trigger: 'blur'
        //   }
        // ],
        // // quit: [{ required: true, message: '请选择是否离职', trigger: 'blur' }],
        // password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
        // // quit_time: [
        // //   { required: true, message: '请选择离职日期', trigger: 'blur' }
        // // ],
        // // description: [
        // //   { required: true, message: '请填写备注', trigger: 'blur' }
        // // ]
        // // register_time: [
        // //   { required: true, message: "请选择注册时间", trigger: "change" }
        // // ]
      },
    };
  },
  // watch: {
  //   atclik: function(val, oldval) {
  //     let newindex = val.indexOf('*'),
  //       oldindex = oldval.indexOf('*')
  //     if (newindex != -1 && oldindex == -1 && val.length > 1) {
  //       this.atclik = ['*']
  //     } else if (newindex != -1 && oldindex != -1 && val.length > 1) {
  //       this.atclik.splice(val.indexOf('*'), 1)
  //     }
  //   }
  // },
  created() {
    this.time();
  },
  methods: {
    // 当前时间
    time() {
      var date = new Date();
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      var d = date.getDate();
      var h = date.getHours();
      var mm = date.getMinutes() + 1;
      var s = date.getSeconds() + 1;
      this.newTime = `${y}-${m}-${d} ${h}:${mm}:${s} `;
    },
    // 获取一条数据
    openEdit(worker_id) {
      this.loading = true;
      this.formData.atclik = [];
      this.dialogTableVisible = true;
      employee_info(store.getters.token, { person_id: worker_id }).then(
        (res) => {
          this.formData = res.data.data;
          console.log(this.formData,'FFFFFFF');
          this.loading = false;
          // 获取公司数据
          get_list(store.getters.token).then((res) => {
            this.Company_list = res.data.list.data;
          });
          this.company_id_id = res.data.data.company_id;
          // 获取部门数据
          department_get_select(store.getters.token, {
            company_id: this.company_id_id,
          }).then((res) => {
            this.department_list = res.data.list;
          });
          this.$set(this.formData,'atclik',[])
          console.log(this.formData.deviceAuth,'DDDDDD');
          for (let i = 0; i <= this.formData.deviceAuth.length - 1; i++) {
          console.log('执行了',i);
            if (this.formData.deviceAuth[i].count == -1) {
              console.log('------');
              this.formData.atclik.push(this.formData.deviceAuth[i].sn);
                console.log(this.formData.atclik,'ASDSSSSS')
            }
          }
          this.formData.gender = res.data.data.gender.toString();
          this.formData.quit = res.data.data.quit.toString();
          this.formData.image_enc = res.data.data.image_enc.toString();
        }
      );
      // 获取默认班次数据
      get_schedule_list(store.getters.token).then((res) => {
        this.defaultShift = res.data.list.data;
      });
      // 角色权限数据
      getList(store.getters.token).then((res) => {
        this.rolePermissions = res.data.list.data;
      });
      // 获取门禁数据
      push_get_list(store.getters.token).then((res) => {
        this.Equipment = res.data.list.data;
      });
    },
    // 获取部门数据
    CompanyIndex(id) {
      this.formData.department_id = "";
      department_get_select(store.getters.token, { company_id: id }).then(
        (res) => {
          this.department_list = res.data.list;
        }
      );
      this.company_name = this.Company_list.filter(
        (item) => item.id == id
      )[0].company;
    },
    // 授权进入门禁change事件
    selectAll(val) {
      this.valList = val;
    },
    // 修改完成
    submitForm(row_id) {
      this.$refs.formData.validate((valid) => {
        if (!valid) {
          return;
        } else {
          this.EquipmentList = [];
          console.log(this.valList, "this.vallist");
          // if (this.valList.filter(item => {return item === '*'})[0]) {
          //   const data = {
          //     sn: '*',
          //     count: '-1'
          //   }
          //   this.EquipmentList.push(data)
          // }
          // if (this.valList) {
          //   // this.valList.forEach((item) => {
          //   //   this.EquipmentList = []
          //   //   // if (item === '*') {
          //   //   //   const data = {
          //   //   //     sn: '*',
          //   //   //     count: '-1'
          //   //   //   }
          //   //   //   this.EquipmentList.push(data)
          //   //   // } else {
          //   //     const data = {
          //   //       sn: '*',
          //   //       count: '0'
          //   //     }
          //   //     this.EquipmentList.push(data)

          //   // })
          // }
          this.Equipment.forEach((item) => {
            const data = {
              sn: item.sn,
              count: "0",
            };
            this.EquipmentList.push(data);
          });

          this.formData.atclik.forEach((item) => {
            for (const equ of this.EquipmentList) {
              if (equ.sn == item) {
                equ.count = "-1";
              }
            }
          });
          var data = {
            image_enc: false,
            id_no: this.formData.id_no,
            name: this.formData.name,
            face_pic: this.formData.face_pic,
            employee_card_id: this.formData.employee_card_id,
            person_id: this.formData.person_id,
            company_id: this.formData.company_id,
            department_id: this.formData.department_id,
            quit: this.formData.quit,
            // shop_role_id: this.formData.shop_role_id,
            description: this.formData.description,
            quit_time: this.formData.quit_time,
            // schedule_id: this.formData.schedule_id,
            image_type: this.formData.image_type,
            person_ts: this.formData.person_ts,
            gender: this.formData.gender,
            deviceAuth: this.EquipmentList,
          };
          employee_edit(store.getters.token, data).then((res) => {
            if (res.data.status) {
              this.$message.success(this.$t("table.edit_complete"));
              this.$emit("getLists");
              this.dialogTableVisible = false;
            } else {
              this.$message.error(this.$t("table.edit_fail") + res.data.msg);
            }
          });
          // var datalist ={
          //    sn:this.EquipmentList.sn,

          // }
          // device_auth_get_select(store.getters.token, this.EquipmentList).then(res =>{

          // })
        }
      });
    },
    // 关闭弹窗
    closeDia() {
      this.dialogTableVisible = false;
    },
    // 上传图片开始 ================================
    handleAvatarSuccess(res, file) {
      this.formData.face_pic = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error(this.$t("validation.img_tip1"));
      }
      if (!isLt2M) {
        this.$message.error(this.$t("validation.img_tip2"));
      }
      return isJPG && isLt2M;
    },
    img_update(file) {
      const that = this;
      var fileName = "banner_img" + file.file.uid;
      client()
        .put(fileName, file.file)
        .then((result) => {
          that.img = result.url;
          // this.$message.success("图片上传成功！");
          console.log(that.img);
        })
        .catch((err) => {
          // this.$message.error("图片上传失败，原因" + err);
        });
      // 获取base64
      var reader = new FileReader();
      // 创建一个img对象
      var img = new Image();
      reader.readAsDataURL(file.file);
      reader.onload = (e) => {
        this.formData.face_pic = reader.result.split(",")[1];

        img.src = e.target.result;
        // base64地址图片加载完毕后执行
        img.onload = function () {
          // 缩放图片需要的canvas（也可以在DOM中直接定义canvas标签，这样就能把压缩完的图片不转base64也能直接显示出来）
          var canvas = document.createElement("canvas");
          var context = canvas.getContext("2d");
          // 图片原始尺寸
          var originWidth = this.width;
          var originHeight = this.height;
          // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
          var maxWidth = 300,
            maxHeight = 300;
          // 目标尺寸
          var targetWidth = originWidth,
            targetHeight = originHeight;
          // 图片尺寸超过最大尺寸的限制
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更改宽度，按照宽度限定尺寸
              targetWidth = maxWidth;
              targetHeight = Math.round(
                maxWidth * (originHeight / originWidth)
              );
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(
                maxHeight * (originWidth / originHeight)
              );
            }
          }
          // 对图片进行缩放
          canvas.width = targetWidth;
          canvas.height = targetHeight;
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight);
          // 图片压缩
          context.drawImage(img, 0, 0, targetWidth, targetHeight);
          /* 第一个参数是创建的img对象；第二三个参数是左上角坐标，后面两个是画布区域宽高*/
          // 压缩后的base64文件
          var newUrl = canvas.toDataURL("image/jpeg", 0.92);
          that.formData.face_pic = newUrl.split(",")[1];
          that.formData.image_type = newUrl.split(",")[0];
        };
      };
    },
    // 上传图片结束 ================================
    // 多选
    // handleCheckAllChange(val) {
    //   this.checkedCities = val ? cityOptions : []
    //   this.isIndeterminate = false
    // },
    // handleCheckedCitiesChange(value) {
    //   const checkedCount = value.length
    //   this.checkAll = checkedCount === this.cities.length
    //   this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length
    // }
  },
};
</script>

<style scoped>
/* 取消输入框下边距 */
.el-form-item {
  margin-bottom: 15px;
}
.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 2px dashed #cccccc;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  position: absolute;
  left: 50%;
  top: 0;
  transform: translate(-50%,0);
  width: auto;
  height: 178px;
  display: block;
}
</style>
